﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;

#endregion


namespace ESF.General
{
	public static class WindowsServiceHelper
	{
		#region Ejecucion
		
		public static void StartServiceAppSetting<T> () where T : BaseWindowsService, new ()
		{
			StartServiceAppSetting <T> ("ServiceMode");
		}


		public static void StartServiceAppSetting<T> (string pServiceModeAppSettingKey) where T : BaseWindowsService, new ()
		{
			StartService <T> (ReadConfig.GetAppSetting (pServiceModeAppSettingKey, "SERVICE"));
		}

		
		public static void StartService<T> (string pServiceMode) where T : BaseWindowsService, new ()
		{
			if (pServiceMode.ToUpper () == "SERVICE")
			{
				StartAsService <T> ();
				return;
			}

			StartAsConsole <T> ();
		}


		public static void StartAsConsole<T> () where T : BaseWindowsService, new ()
		{
			T svc;
			
			
			try
			{
				svc = new T ();
			
				Console.WriteLine ("Starting Service... (without default timer)");
				
				svc.Test ();

				Console.WriteLine ("Press any key to stop service...");
				Console.ReadLine ();

				Console.WriteLine ("Stopping Service...");
				
				svc.DoStop ();
			}
			catch (Exception pEx)
			{
				Console.Error.WriteLine ("Error: " + pEx.Message);

				Log.Error (pEx);

				Console.WriteLine ("Press any key to stop the test...");
				Console.ReadLine ();
			}
		}
		
		
		public static void StartAsService<T> () where T : ServiceBase, new ()
		{
			try
			{
				ServiceBase.Run (new ServiceBase[] { new T () });
			}
			catch (Exception pEx)
			{
				Log.Error (pEx);
			}
		}
		
		#endregion
	}
}
